//
//  SkeletonAnimationViewController.swift
//  ZSceneDemo
//
//  Created by 张鑫 on 2020/9/2.
//  Copyright © 2020 www.lionaitech.com. All rights reserved.
//

import UIKit

import SceneKit

class SkeletonAnimationViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        createScene()
        
        removeAnimations()
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(locolTestAction))
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
    }
    
    @objc func locolTestAction() {
        getAnimations()
    }
    
    var sceneSource: SCNSceneSource?
    var scene: SCNScene?
    func createScene() {
        //设置摄像机架设点
        let cameraNode = SCNNode()
        
        cameraNode.camera = SCNCamera()
        cameraNode.camera?.automaticallyAdjustsZRange = true
        cameraNode.position = SCNVector3(0, 1000, 3000)
        cameraNode.camera?.zFar = 20000
//        cameraNode.rotation = SCNVector4(1, 0, 0, -Double.pi/16)
        
        
        //设置光源点
        let lightNode = SCNNode()
        lightNode.light = SCNLight()
        lightNode.light?.type = .omni
        lightNode.position = SCNVector3(0, 10, 10)
        
        //设置周围环境
        let ambientLightNode = SCNNode()
        ambientLightNode.light = SCNLight()
        ambientLightNode.light?.type = .ambient
        ambientLightNode.light?.color = UIColor.lightGray
        
        guard let url = Bundle.main.url(forResource: "art.scnassets/skinning/skinning", withExtension: "dae") else {
            print("scene load failed")
            return
        }
        sceneSource = SCNSceneSource(url: url, options: nil)
        
        scene = sceneSource?.scene(options: nil)
        scene?.rootNode.addChildNode(cameraNode)
        //scene?.rootNode.addChildNode(lightNode)
        //scene?.rootNode.addChildNode(ambientLightNode)
        
        let threeDView = SCNView(frame: CGRect.zero)
        threeDView.translatesAutoresizingMaskIntoConstraints = false
        threeDView.scene = scene
        threeDView.allowsCameraControl = true
        threeDView.showsStatistics = true
        threeDView.backgroundColor = UIColor.black
        threeDView.preferredFramesPerSecond = 30
        view.addSubview(threeDView)
        
        
        threeDView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        threeDView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
        threeDView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
        threeDView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
    }
    
    
    func removeAnimations(node: SCNNode? = nil) {
        if let n = node {
            
            print("\(n.name) ========== \(n.animationKeys)")
            n.removeAllAnimations()
            for n in n.childNodes {
                removeAnimations(node: n)
            }
        } else if let n = scene?.rootNode {
            removeAnimations(node: n)
        }
    }
    
    func getAnimations() {
        
        
        guard let animationIDs = sceneSource?.identifiersOfEntries(withClass: CAAnimation.self) else {
            print("animation id is nil")
            return
        }
        print("============\(animationIDs)")
        
        var duration: Double = 0
        
        var animationList = [CAAnimation]()
        for id in animationIDs {
            guard let animation = sceneSource?.entryWithIdentifier(id, withClass: CAAnimation.self) else {
                print("animation is nil for == \(id)")
                continue
            }
            duration = max(animation.duration, duration)
            animationList.append(animation)
        }
        /**
         动画帧可以单独提取使用
         其中"animation/1" 是一个完整的动画
         后面的都是某个骨骼的动画
         let id = ["animation/1", "keyframedAnimations/1", "keyframedAnimations/2", "keyframedAnimations/3", "keyframedAnimations/4", "keyframedAnimations/5", "keyframedAnimations/6", "keyframedAnimations/7", "keyframedAnimations/8", "keyframedAnimations/9", "keyframedAnimations/10", "keyframedAnimations/11", "keyframedAnimations/12", "keyframedAnimations/13", "keyframedAnimations/14", "keyframedAnimations/15", "keyframedAnimations/16", "keyframedAnimations/17", "keyframedAnimations/18", "keyframedAnimations/19", "keyframedAnimations/20", "keyframedAnimations/21", "keyframedAnimations/22", "keyframedAnimations/23"][6]
         if let animation = sceneSource?.entryWithIdentifier(id, withClass: CAAnimation.self) {
             duration = max(animation.duration, duration)
             animationList.append(animation)
         }
         
         单独完整动画提取
         guard let animationGroup = sceneSource?.entryWithIdentifier("animation/1", withClass: CAAnimation.self) else {
             return
         }
         animationGroup.duration = animationGroup.duration - 20
         animationGroup.timeOffset = 20
         */
        
        let animationGroup = CAAnimationGroup()
        animationGroup.animations = animationList
        animationGroup.duration = duration - 20
        animationGroup.timeOffset = 20
        animationGroup.isRemovedOnCompletion = true
        animationGroup.repeatCount = MAXFLOAT
        
        let node = scene?.rootNode.childNode(withName: "avatar_attach", recursively: true)
        node?.addAnimation(animationGroup, forKey: "animation")
        
        
        
        
        
        
    }
}
